<?php
namespace app\api\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use app\common\MobileVerify\MobileVerify;
use think\facade\Cache;
class Login extends Base{
    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->MemberLoginModel=new \app\common\model\MemberLoginModel();
    }
    public function login(){
        $data=Request::param();
        $validate = \think\facade\Validate::rule(['mobile'=>'require|mobile','verfiyCode'=>'require'])->message([
            "mobile.require"=>"请填写手机号码",
            "mobile.mobile"=>"手机号码不正确",
            "verfiyCode.require"=>"请填写验证码"
        ]);
        if (!$validate->check(Request::param())) {
            $this->error($validate->getError());
        }
        //验证
        $code = new MobileVerify();
        if(!$code->check($data['mobile'],$data['verfiyCode'])){
            $this->error($code->error);
        }
        $code->clear();//清空验证码
        //判断会员是否存在
        $member=Db::name("member")->where("mobile",$data['mobile'])->find();
        if(!$member){
            $this->error("当前用户不存在");
        }
        //设置登录
        $token=$this->MemberLoginModel->SetLoginToken($member['member_id'],$data['device']);
        //更新会员表最后一次登录的信息
        $this->MemberLoginModel->SetLastLoginInfo($member['member_id']);
        $this->success([
            "member_id"=>$member['member_id'],
            "mobile"=>$member['mobile'],
            "device"=>$data['device'],
            "token"=>$token,
            "truename"=>$member['truename'],
            "school"=>$member['school'],
        ]);

    }
    public function test(){
        $this->MemberLoginModel->SetLoginToken(1,"wei","abcd");
    }
    public function test2(){
        echo Cache::get("verify_mobile_code");
    }
    //发送验证码
    public function verfiyCode(){
        $mobile=Request::param("mobile");
        $validate = \think\facade\Validate::rule('mobile', 'require|mobile')->message(["mobile.require"=>"请填写手机号码","mobile.mobile"=>"手机号码不正确"]);
        if (!$validate->check(Request::param())) {
            $this->error($validate->getError());
        }
        //判断会员是否存在
        $member=Db::name("member")->where("mobile",$mobile)->find();
        if(!$member){
            $this->error("当前用户不存在");
        }
        //
        $code = new MobileVerify();
        $result=$code->send_code($mobile);
        if($result){
            $this->success("短信发送成功");
        }else{
            $this->error($code->error);
        }
    }

}
